<?php

namespace App\Http\Controllers\Guard\Car;

use App\Http\Controllers\Common\GuardController;
use App\Models\Car\CarInfo;
use App\Models\Car\Order;
use App\Models\Car\RentUnit;
use App\Models\Constant\CarConstant;
use Illuminate\Http\Request;

class IndexController extends GuardController{

    public function getCountCarInfo(Request $request){
        $cars = CarInfo::query()->get();
        $count_car = $cars->count();
        $count_rent_car = $cars->where('status',CarConstant::CAR_STATUS_BUSY)->count();
        $count_fixing_car = $cars->where('status',CarConstant::CAR_STATUS_FIXING)->count();
        $count_free_car = $cars->where('status',CarConstant::CAR_STATUS_FREE)->count();

        $count_insurance_car = $cars->where('insurance_date','>=',date('Y-m-d'))
            ->where('insurance_date','<=',date('Y-m-d',strtotime('+30 days')))->count();

        return responseSuccess(compact('count_car','count_rent_car','count_fixing_car','count_free_car','count_insurance_car'));
    }

    public function getCountRentInfo(Request $request){
        $records = Order::query()->get(['rent_unit_id','car_count']);
        $res = [];
        $temp = [];

        foreach ($records as $record) {
            if(isset($res[$record->rent_unit_id])){
                $temp[$record->rent_unit_id]+=$record->car_count;
            }else{
                $temp[$record->rent_unit_id] = $record->car_count;
            }
        }

        //排序
        uasort($temp,function ($a,$b){
            return $a<$b;
        });

        //取前10个元素
        $countTop = 0;
        foreach ($temp as $k=>$v){
            $res[$k] = $v;
            $countTop++;
            if ($countTop>=10)break;
        }

        $top = [];
        foreach ($res as $rent_unit_id=>$rent_car_count){
            $top[] = [
                'rent_unit_id'=>$rent_unit_id,
                'rent_unit_name'=>RentUnit::query()->find($rent_unit_id)->unit_name??'未知',
                'rent_car_count'=>$rent_car_count
            ];
        }

        return responseSuccess($top);
    }
}
